<template>
  <div id="login">
    <van-nav-bar title="黑马头条 - 登录" :fixed="true" />
    <van-form @submit="login">
      <van-field
        v-model="form.mobile"
        type="tel"
        label="手机号码"
        placeholder="请输入手机号码"
        :rules="rules.mobile"

      />
      <van-field
        v-model="form.code"
        type="password"
        label="登录密码"
        placeholder="请输入密码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/userAPI'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      form: {
        mobile: '13888888888',
        code: '246810'
      },
      // 表单校验的规则
      rules: {
        mobile: [
          {
            required: true,
            message: '请正确填写手机号码',
            trigger: onblur
          },
          {
            pattern: /^1\d{10}$/,
            message: '请填写正确的手机号',
            trigger: onblur
          }
        ],
        code: [
          {
            required: true,
            message: '请正确填写密码',
            trigger: onblur
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async login() {
      // 只有当表单数据校验通过之后，才会调用此Login函数
      const { data: res } = await loginAPI(this.form)
      console.log(res.data.data)
      if (res.message === 'OK') {
        // 3. 把登录成功的结果，存储到 vuex 中
        this.updateTokenInfo(res.data)
        // 4. 登录成功后，跳转到主页
        this.$router.push('/')
      }
    }
  }
}
</script>

<style lang="less" scoped>
#login {
  padding-top: 46px;
}
</style>
